'use client'

import { z } from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { type Rule } from '../data/schema'
import { getRouteApi, useRouter } from '@tanstack/react-router'
import { TreeSelectDropdown } from '@/components/tree-select'
import { toast } from 'sonner'
import { useRuleAdd, useRuleEdit } from '@/api/rules'
const formSchema = z
  .object({
    pid: z.number(),
    title: z.string().min(1, 'Title is required.'),
    key: z.string().min(1, 'key is required.'),
    icon: z.string(),
    href: z.string().min(1, 'href is required.'),
    type: z.number(),
    weight: z.number(),
    isEdit: z.boolean(),
  })

type TableForm = z.infer<typeof formSchema>

interface Props {
  currentRow?: Rule
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function TableActionDialog({ currentRow, open, onOpenChange }: Props) {
  const router = useRouter()
  const isEdit = !!currentRow
  const form = useForm<TableForm>({
    resolver: zodResolver(formSchema),
    defaultValues: isEdit
      ? {
        ...currentRow,
        isEdit,
      }
      : {
        pid: 0,
        title: '',
        key: '',
        icon: '',
        href: '',
        type: 0,
        weight: 0,
        isEdit,
      },
  })

  const ruleAdd = useRuleAdd()
  const ruleEdit = useRuleEdit()
  const onSubmit = (values: TableForm) => {
    if (currentRow) {
      ruleEdit.mutate({ ...currentRow, ...values }, {
        onSuccess: () => {
          onOpenChange(false)
          form.reset()
          router.invalidate();
          toast.success('Rule Updated')
        }
      })
    } else {
      ruleAdd.mutate(values, {
        onSuccess: () => {
          onOpenChange(false)
          form.reset()
          router.invalidate();
          toast.success('Rule Saved')
        },
      })
    }

  }
  const routeApi = getRouteApi('/_authenticated/rules/')
  const { ruleSelect, ruleList } = routeApi.useLoaderData()

  return (
    <Dialog
      open={open}
      onOpenChange={(state) => {
        form.reset()
        onOpenChange(state)
      }}
    >
      <DialogContent className='sm:max-w-lg'>
        <DialogHeader className='text-left'>
          <DialogTitle>{isEdit ? 'Edit Rule' : 'Add New Rule'}</DialogTitle>
          <DialogDescription>
            {isEdit ? 'Update the Rule here. ' : 'Create new Rule here. '}
            Click save when you&apos;re done.
          </DialogDescription>
        </DialogHeader>
        <div className='-mr-4 h-[26.25rem] w-full overflow-y-auto py-1 pr-4'>
          <Form {...form}>
            <form
              id='rule-form'
              onSubmit={form.handleSubmit(onSubmit)}
              className='space-y-4 p-0.5'
            >
              <FormField
                control={form.control}
                name='title'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Title
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder='rule name'
                        className='col-span-4'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='key'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      key
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder='rule key'
                        className='col-span-4'
                        autoComplete='off'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='pid'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Parent Rule
                    </FormLabel>
                    <TreeSelectDropdown
                      defaultValue={field.value.toString()}
                      onValueChange={(value) => field.onChange(parseInt(value))}
                      placeholder='Select parent rule'
                      className='col-span-4 text-muted-foreground'
                      treeItems={ruleSelect}
                      listItems={ruleList}
                      enableSubSelection={false}
                    />
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='href'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Url
                    </FormLabel>
                    <FormControl>
                      <Input
                        className='col-span-4'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='icon'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Icon
                    </FormLabel>
                    <FormControl>
                      <Input
                        className='col-span-4'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='type'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Type
                    </FormLabel>
                    <FormControl>
                      <Input
                        className='col-span-4'
                        {...field}
                        type='number'
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name='weight'
                render={({ field }) => (
                  <FormItem className='grid grid-cols-6 items-center space-y-0 gap-x-4 gap-y-1'>
                    <FormLabel className='col-span-2 text-right'>
                      Sort
                    </FormLabel>
                    <FormControl>
                      <Input
                        className='col-span-4'
                        {...field}
                      />
                    </FormControl>
                    <FormMessage className='col-span-4 col-start-3' />
                  </FormItem>
                )}
              />

            </form>
          </Form>
        </div>
        <DialogFooter>
          <Button type='submit' form='rule-form'>
            Save changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
